package com.xunker.appointment.utils;

import org.springframework.beans.BeansException;

import org.springframework.beans.FatalBeanException;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;


import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

public class BeanUtils extends org.springframework.beans.BeanUtils {
    public static void copyBean(Object source,Object target,Class<?> editable,String... ignoreProperties) throws BeansException{
        Assert.notNull(source,"来源bean不能未空");
        Assert.notNull(target,"目标bean不能未空");
        Class<?> actualEditable=target.getClass();
        if (editable!=null){
            if (!editable.isInstance(target)){
                throw new IllegalArgumentException("目标类["+target.getClass().getName()+"] not assignable to Editable class ["+editable.getName()+"]");
            }
            actualEditable=editable;
        }
        PropertyDescriptor[] targetPds= getPropertyDescriptors(actualEditable);
        List<String> ignoreList=(ignoreProperties!=null)? Arrays.asList(ignoreProperties) : null;
        for (PropertyDescriptor targetPd : targetPds) {
            Method writeMethod = targetPd.getWriteMethod();
            if(writeMethod!=null&&(ignoreProperties==null||(!ignoreList.contains(targetPd.getName())))){
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if(sourcePd!=null){
                    Method readMethod = sourcePd.getReadMethod();
                    if(readMethod!=null&& ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],readMethod.getReturnType())){
                        try{
                            if(!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())){
                                readMethod.setAccessible(true);
                            }
                            Object invoke = readMethod.invoke(source);
                            if(invoke!=null){
                                if(!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())){
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target,invoke);
                            }
                        }catch (Throwable ex){
                            throw new FatalBeanException("不能复制配置 '"+targetPd.getName()+"' 从来源类到目标类",ex);
                        }
                    }
                }
            }
        }
    }
}
